﻿using System.Security.Cryptography;
using System;
using System.Web.Security;
using System.Text;

namespace MyLab.Utilities
{
    public class PasswordUtil
    {
        public static readonly PasswordUtil Instance = new PasswordUtil();

        public virtual string EncryptPassword(string password)
        {
            return FormsAuthentication.HashPasswordForStoringInConfigFile(password, "MD5");
        }

        public virtual string EncodePassword(string password, string salt)
        {
            byte[] passwordBytes = Encoding.Unicode.GetBytes(password);
            byte[] saltBytes = Convert.FromBase64String(salt);
            byte[] dataBytes = new byte[passwordBytes.Length + saltBytes.Length];

            Buffer.BlockCopy(passwordBytes, 0, dataBytes, 0, passwordBytes.Length);
            Buffer.BlockCopy(saltBytes, 0, dataBytes, passwordBytes.Length, saltBytes.Length);

            string hashedString = Convert.ToBase64String(dataBytes);

            return EncryptPassword(hashedString);
        }

        public virtual string GeneratePasswordSalt()
        {
            byte[] data = new byte[0x10];
            RNGCryptoServiceProvider.Create().GetBytes(data);

            return Convert.ToBase64String(data);
        }
    }
}
